
class OrdersController < ApplicationController
  before_filter :authorize
  # GET /orders
  # GET /orders.xml
  def index
    if admin?
      @orders = Order.paginate :order => 'created_at DESC', :page => params[:page]
    else
      @orders = Order.paginate_by_user cur_user.name,:order => 'created_at DESC', :page => params[:page]
    end
    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @orders }
    end
  end

  # GET /orders/1
  # GET /orders/1.xml
  def show
    @order = Order.find(params[:id])
    return if cannt_do_by @order.user
    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @order }
    end
  end

  # GET /orders/new
  # GET /orders/new.xml
  def new
    @order = Order.new
        
    respond_to do |format|
      format.html { render :template => 'store/order_lines_edit'}
      format.xml  { render :xml => @order }
    end
  end

  # GET /orders/1/edit
  def edit
    @order = Order.find(params[:id])
    cannt_do_by @order.user
  end

  # POST /orders
  # POST /orders.xml
  def create
    @order = Order.new(params[:order])
    @order.user = cur_user_name
    respond_to do |format|
      if @order.save
        flash[:notice] = '订单保存成功.'
        format.html { redirect_to_order(@order) }
        format.xml  { render :xml => @order, :status => :created, :location => @order }
      else
        format.html { render :template => 'store/order_lines_edit' }
        format.xml  { render :xml => @order.errors, :status => :unprocessable_entity }
      end
    end
  end

  # PUT /orders/1
  # PUT /orders/1.xml
  def update
    @order = Order.find(params[:id])
    return if cannt_do_by @order.user
    respond_to do |format|
      if @order.update_attributes(params[:order])
        flash[:notice] = '订单更新成功.'
        format.html { redirect_to_order(@order) }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @order.errors, :status => :unprocessable_entity }
      end
    end
  end

  # DELETE /orders/1
  # DELETE /orders/1.xml
  def destroy
    @order = Order.find(params[:id])
    return if cannt_do_by @order.user
    @order.destroy

    respond_to do |format|
      format.html { redirect_to(orders_url) }
      format.xml  { head :ok }
    end
  end
  
  private 
  def redirect_to_order order
    redirect_to :controller => 'store', :action => 'order_lines', :id => order.order_num
  end


end
